<template>
    <div>
        <div class="handleBtnCont" style="padding-top: 10px">
            <el-button size="mini" type="primary" @click="createDir">添加章节</el-button>
        </div>
        <div class="cardbox">
            <el-card class="box-card" shadow="hover" v-for="(item, index) in dirList" :key="item.id || index">
                <div slot="header" class="clearfix">
                    <div class="cardbox-header">
                        <div>
                            <div v-if="!isEditNameState" class="cardbox-header-item">
                                <div>{{ item.title }}</div>
                                <el-button type="text" @click="isEditNameState = true">编辑</el-button>
                            </div>
                            <div v-else class="cardbox-header-item">
                                <el-input v-model="item.title" />
                                <el-button type="text" @click="isEditNameState = false">确定</el-button>
                            </div>
                        </div>
                        <el-button style="float: right; padding: 3px 0" type="text">
                            <el-button title="添加" type="primary" size="mini" icon="el-icon-plus" circle
                                @click="fileDialog(index)" />
                            <el-button title="删除" size="mini" icon="el-icon-delete" circle @click="removeDir(index)" />
                            <el-button title="下移" size="mini" icon="el-icon-sort-down" circle
                                @click="sortDownDir(index)" />
                            <el-button title="上移" size="mini" icon="el-icon-sort-up" circle @click="sortUpDir(index)" />
                        </el-button>
                    </div>
                </div>
                <el-table :data="item.fileList" :expand-row-keys="computedExpand" row-key="id" border stripe>
                    <el-table-column label="文件名称">
                        <template v-slot="scope">
                            <el-input v-model="scope.row.title" placeholder="请输入文件名称" size="mini"></el-input>
                        </template>
                    </el-table-column>
                    <el-table-column prop="fileType_dictText" label="课件类型" align="center" width="160px" />
                    <el-table-column label="要求时长" align="center" width="200px">
                        <template v-slot="scope">
                            <div style="display: flex; justify-content: center">
                                <second-set v-model="scope.row.needLearn" />
                            </div>
                        </template>
                    </el-table-column>

                    <el-table-column label="学完积分" align="center" width="200px">
                        <template v-slot="scope">
                            <el-input-number v-model="scope.row.points" :min="0" :max="99999" size="mini" />
                        </template>
                    </el-table-column>

                    <el-table-column align="center" label="操作" width="220px">
                        <template v-slot="sub">
                            <el-button title="移除" size="mini" icon="el-icon-delete" type="danger" circle
                                @click="removeFile(sub.row, sub.$index)" />
                            <el-button title="下移" size="mini" icon="el-icon-sort-down" circle
                                @click="sortDownFile(item.fileList, sub.$index)" />
                            <el-button title="上移" size="mini" icon="el-icon-sort-up" circle
                                @click="sortUpFile(item.fileList, sub.$index)" />
                            <el-button title="预览" size="mini" icon="el-icon-view" type="primary" circle
                                @click="handlePreview(sub.row)" />
                        </template>
                    </el-table-column>
                </el-table>
            </el-card>
        </div>
        <!-- 文件选择弹窗 -->
        <course-file-dialog ref="childComponent" :visible.sync="dialogVisible" :excludes="excludes"
            @select="dialogSelect" />
    </div>
</template>

<script>
import { uuid } from "vue-uuid";
import SecondSet from "@/components/SecondSet";
import CourseFileDialog from "@/components/CourseFileDialog";

export default {
    name: "ChapterManagement",
    components: {
        SecondSet,
        CourseFileDialog
    },
    props: {
        value: {
            type: Array,
            default: () => []
        }
    },
    data() {
        return {
            isEditNameState: false,
            dialogVisible: false,
            excludes: [],
            dirList: [],
            curIndex: -1 // 当前操作的目录索引
        };
    },
    computed: {
        computedExpand() {
            const arr = [];
            this.dirList.map((item) => {
                if (item.fileList && item.fileList.length > 0) {
                    arr.push(item.id);
                }
            });
            return arr;
        }
    },
    watch: {
        value: {
            handler(val) {
                this.dirList = val;
                this.$emit("updateFileList", val);
            },
            deep: true,
            immediate: true
        },
        dirList: {
            handler(val) {
                this.$emit("input", val);
                this.processExcludes();
            },
            deep: true
        }
    },
    methods: {
        // 创建目录
        createDir() {
            this.$prompt("请输入知识点名称", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消"
            }).then(({ value }) => {
                for (let i = 0; i < this.dirList.length; i++) {
                    if (this.dirList[i].title === value) {
                        this.$message.error(`知识点名称：${value}重复了，请换一个！`);
                        return;
                    }
                }
                this.dirList.push({ title: value, fileList: [] });
            });
        },

        // 批量添加目录
        batchAddDir(data) {
            if (data.length > 0) {
                const newArr = [];
                data.map((oItem) => {
                    oItem.content.map((item, index) => {
                        if (this.dirList.filter((dItem) => dItem.title == item.point).length > 0) {
                            return;
                        }
                        newArr.push({
                            title: item.point,
                            fileList: [],
                            id: parseInt(Math.random() * 100000) + String(index + 1)
                        });
                    });
                });

                this.dirList = this.dirList.concat(newArr);
            }
        },

        // 打开文件选择对话框
        fileDialog(index) {
            this.curIndex = index;
            this.dialogVisible = true;
        },

        // 文件选择后的回调
        dialogSelect(objs) {
            if (objs != null && objs.length > 0) {
                for (let i = 0; i < objs.length; i++) {
                    this.dirList[this.curIndex].fileList.push({
                        fileId: objs[i].id,
                        fileUrl: objs[i].fileUrl,
                        title: objs[i].title,
                        fileType: objs[i].fileType,
                        fileType_dictText: objs[i].fileType_dictText,
                        needLearn: objs[i].duration,
                        points: 0
                    });
                }
            }
        },

        // 移除目录
        removeDir(index) {
            this.dirList.splice(index, 1);
        },

        // 移除文件
        removeFile(row, index) {
            // 通过父级找到对应的 fileList
            const parent = this.dirList.find((item) => item.fileList.includes(row));
            if (parent) {
                parent.fileList.splice(index, 1);
            }
        },

        // 目录下移
        sortDownDir(dirIndex) {
            const newIndex = dirIndex + 1;
            const targetIndex = this.dirList.splice(dirIndex, 1)[0];
            this.dirList.splice(newIndex, 0, targetIndex);
        },

        // 目录上移
        sortUpDir(dirIndex) {
            const newIndex = dirIndex - 1;
            const targetIndex = this.dirList.splice(dirIndex, 1)[0];
            this.dirList.splice(newIndex, 0, targetIndex);
        },

        // 文件下移
        sortDownFile(fileList, fileIndex) {
            const newIndex = fileIndex + 1;
            const targetIndex = fileList.splice(fileIndex, 1)[0];
            fileList.splice(newIndex, 0, targetIndex);
        },

        // 文件上移
        sortUpFile(fileList, fileIndex) {
            const newIndex = fileIndex - 1;
            const targetIndex = fileList.splice(fileIndex, 1)[0];
            fileList.splice(newIndex, 0, targetIndex);
        },

        // 处理已在列表的文件，避免重复加入
        processExcludes() {
            const ids = [];
            for (let i = 0; i < this.dirList.length; i++) {
                const files = this.dirList[i].fileList;
                for (let j = 0; j < files.length; j++) {
                    ids.push(files[j].fileId);
                }
            }
            this.excludes = ids;
        },

        // 预览文件
        handlePreview(data) {
            this.$emit('preview', data);
        }
    }
};
</script>

<style scoped lang="scss">
.handleBtnCont {
    padding-bottom: 20px;

    /deep/.el-button--success::before {
        content: "";
        width: 60px;
        height: 18px;
        background: url("../../../../../assets/exam/corner_mark.png") no-repeat;
        background-size: 100% 100%;
        position: absolute;
        top: -50%;
        right: -50%;
    }
}

.cardbox {
    display: flex;
    flex-direction: column;
    gap: 12px;
}

.cardbox-header {
    display: flex;
    justify-content: space-between;
}

.cardbox-header-item {
    display: flex;
    align-items: center;
    gap: 12px;
}
</style>
